$(document).ready(function () {

    /* our model structure and default values */
    function AppViewModel() {
        var self = this;
        self.toggle = false;
        self.toggleBool = function () {
            return (self.toggle = !self.toggle);
        }
        self.loading = ko.observable(false);
        self.songListPage = ko.observable(false);
        self.uploadPage = ko.observable(false);
        self.songPage = ko.observable(false);

        /* upload variables */
        self.uploadPercent = ko.observable('0%');
        self.uploadStatus = ko.observable('');

        self.songArray = ko.observableArray( /* the songArray list */
					[
						{ title: '', songId: 0, filename: '', guitarPartyId: '', artist: '', album: '', genre: '' }
					]);

        /* guitarparty variables */
        self.guitarSelectSongSection = ko.observable(false);
        self.guitarLoading = ko.observable(false);
        self.guitarSongInformation = ko.observable(false);
        self.guitarSelectArtistSection = ko.observable(false);
        self.guitarArtistInformation = ko.observable(false);
        self.displaySongMessage = ko.observable(false);
        self.songID3SaveDisplay = ko.observable(false);
        self.updateTagsPage = ko.observable(false);
        self.songMessage = ko.observable();
        self.searchSongArrayString = ko.observable(); /* stores the search string when searching the array */
        self.searchSongListArray = ko.observableArray([]);
        self.guitarPartyArray = ko.observableArray([]); /* the guitarparty search result when searching for a song */
        self.guitarPartArtistArray = ko.observableArray([]); /* array for the artist search result from guitarparty */
        self.guitarSearchString = ko.observable();
        self.guitarArtistSearchString = ko.observable();
        self.guitarSelectedArtist = ko.observable();
        self.guitarApiKey = ko.observable("318bcdf3db8c9077abd46d90820a77db7edf59a4");
        self.guitarSelectedSong = ko.observable();
        self.guitarSongName = ko.observable();
        self.songFileName = ko.observable();
        self.guitarSongUri = ko.observable();
        self.guitarSongLyrics = ko.observable(); /* guitarparty body field */
        self.guitarArtistUri = ko.observable();
        self.guitarArtistName = ko.observable();
        self.guitarArtistBio = ko.observable();
        self.editSongAlbum = ko.observable();
        self.editSongGenre = ko.observable();

        self.resetSongPage = function () {
            self.songID3SaveDisplay(false);
            self.displaySongMessage(false);
            self.songMessage('');
            self.guitarSongInformation(false);
            /* self.guitarSearchString(''); */
            /* self.guitarSelectedSong(''); */
            self.guitarSongName('');
            self.guitarSongUri('');
            self.guitarArtistName('');
            self.guitarArtistUri('');
            self.guitarArtistBio('');
            self.guitarSongLyrics(''); /* guitarparty body field */

        };

        self.totalSongs = ko.computed(function () {
            return self.searchSongListArray().length;
        });

        self.sortBySong = function () { /* for sorting the table by price did not get this to work with the grid*/
            self.searchSongListArray.sort(function (a, b) {
                return a.title < b.title ? -1 : 1;
            });
        };

        self.sortByArtist = function () { /* for sorting the table by price did not get this to work with the grid*/
            self.searchSongListArray.sort(function (a, b) {
                return a.artist < b.artist ? -1 : 1;
            });
        };

        self.sortByAlbum = function () { /* for sorting the table by price did not get this to work with the grid*/
            self.searchSongListArray.sort(function (a, b) {
                return a.album < b.album ? -1 : 1;
            });
        };

        self.uploadPageClick = function () {
            self.songPage(false);
            self.songListPage(false);
            self.uploadPage(true);
        };

        self.songListPageClick = function () {
            self.songPage(false);
            self.uploadPage(false);
            self.songListPage(true);
        };

        self.songPageClick = function () {
            self.uploadPage(false);
            self.songListPage(false);
            self.songPage(true);
        };

        /* function that gets all the song user has uploaded */
        self.refreshClick = function () {
            self.loading(true);
            $.getJSON("/api/song", function (data) {
                self.songArray(data);
                self.searchSongListArray(data);
                self.songListPage(true);
                self.loading(false); /* hide the loading image */
            });
        };

        self.searchSongArray = function () {
            if (self.searchSongArrayString()) { /* if there is a search string */
                srch = self.searchSongArrayString().toLowerCase(); /* for convenience */
                console.log("Search string: " + srch);
                console.log("Array length: " + self.songArray().length);
                var results = []; /* create an empty to store the results */
                for (var i = 0; i < self.songArray().length; i++) {
                    var s = self.songArray()[i]; /* for convenience */
                    var add = false; /*resets to false in each iteration */
                    if (s.title) {
                        if (s.title.toLowerCase().indexOf(srch) >= 0)
                            add = true;
                    }

                    if (s.artist) {
                        if (s.artist.toLowerCase().indexOf(srch) >= 0)
                            add = true;
                    }

                    if (s.album) {
                        if (s.album.toLowerCase().indexOf(srch) >= 0)
                            add = true;
                    }

                    /* then if add == true song item to the result array */
                    if (add) {
                        results.push(s);
                    }
                }
                results.push(s); /* then push the item to the observable array */
                self.searchSongListArray(results);
            }
        };

        self.searchGuitarArtist = function () {
            if (self.guitarArtistSearchString()) { /* if there is a value in artist search string */
                $.ajaxSetup({
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Guitarparty-Api-Key', self.guitarApiKey());
                    }
                });

                /* Searching GuitarParty.com for the selected song */
                $.getJSON("http://api.guitarparty.com/v2/artists/?query=" + self.guitarArtistSearchString(), function (data) {
                    self.guitarPartArtistArray(data.objects); /* populate the observableArray */
                    self.guitarLoading(false);
                    if (parseInt(data.objects_count) == 1) {
                        /* TODO: display the artist info */
                        self.searchGuitarArtistSingle();
                    }
                    else if (parseInt(data.objects_count) > 1) {
                        self.guitarSelectArtistSection(true);
                    }
                    else {
                        self.songMessage("Artist with name: " + self.guitarArtistSearchString() + " not found...");
                        self.displaySongMessage(true);
                    }
                });
            }
        };

        /* a function that gets a single song from guitarparty.com */
        self.searchGuitarArtistSingle = function () {
            if (self.guitarSelectedArtist().uri) { /* if there is an uri value */
                /* prepare the ajax request call http://api.guitarparty.com/v2/artists/1/ */

                self.guitarLoading(true);

                $.ajaxSetup({
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Guitarparty-Api-Key', self.guitarApiKey());
                    }
                });

                /* The ajax call */
                $.getJSON("http://api.guitarparty.com" + self.guitarSelectedArtist().uri, function (data) {
                    self.guitarArtistUri(data.uri);
                    self.guitarArtistName(data.name);
                    self.guitarArtistBio(data.bio);
                    self.guitarLoading(false);
                    self.guitarSelectArtistSection(false);
                    self.guitarArtistInformation(true);
                    self.songID3SaveDisplay(true);

                }); /* close getJSON */
            }
        }; /* close self.searchGuitarArtistSingle */

        self.searchGuitarParty = function () {
            if (self.guitarSearchString()) { /* if there is a song search value */
                self.resetSongPage(); /* reset songpage field values */
                /* prepare the ajax request call */
                self.guitarLoading(true);
                self.guitarSelectSongSection(false);

                $.ajaxSetup({
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Guitarparty-Api-Key', self.guitarApiKey());
                    }
                });

                /* Searching GuitarParty.com for the selected song */
                $.getJSON("http://api.guitarparty.com/v2/songs/?query=" + self.guitarSearchString(), function (data) {
                    self.guitarPartyArray(data.objects); /* populate the observableArray */
                    self.guitarLoading(false);
                    if (parseInt(data.objects_count) == 1) /* if only one song is found the display the lyrics */
                    {
                        self.searchGuitarPartySingle();
                    }
                    else if (parseInt(data.objects_count) > 1) {
                        self.guitarSelectSongSection(true);
                    }
                    else {
                        self.songMessage("Song with name: " + self.guitarSearchString() + " not found...");
                        self.displaySongMessage(true);
                    }
                });
            }
        };

        /* a function that gets a single song from guitarparty.com */
        self.searchGuitarPartySingle = function () {
            if (self.guitarSelectedSong().uri) { /* if there is a search uri value */
                /* prepare the ajax request call http://api.guitarparty.com/v2/songs/5/ */

                self.guitarLoading(true);

                $.ajaxSetup({
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Guitarparty-Api-Key', self.guitarApiKey());
                    }
                });

                /* The ajax call */
                $.getJSON("http://api.guitarparty.com" + self.guitarSelectedSong().uri, function (data) {
                    console.log(data.title + '\n' + data.body);
                    self.guitarSongName(data.title);
                    self.guitarSongLyrics(data.body);
                    self.guitarSongUri(data.uri);
                    self.guitarLoading(false);
                    self.guitarSelectSongSection(false);
                    self.guitarSongInformation(true);
                    self.songID3SaveDisplay(true);

                }); /* close getJSON */
            }
        }; /* close self.searchGuitarPartySingle */


        self.saveSongID3 = function () {
            /* first create the json object */
            var jsonObj = {
                "title": self.guitarSongName(),
                "songId": self.songFileName(),
                "filename": self.songFileName(),
                "guitarPartyId": self.guitarSongUri(),
                "artist": self.guitarArtistName(),
                "album": self.editSongAlbum(),
                "genre": self.editSongGenre()
            };
            console.log(jsonObj);

            $.ajax({
                type: "PUT",
                method: "PUT",
                dataType: "jsonp",
                contentType: "application/json",
                url: "/api/song/",
                data: jsonObj,
                success: function (data) {
                    //$.parseJSON(data);
                    console.log("Got data");
                },
                error: function () {
                    console.log("error");
                }
            });

        }; /* close the saveSongID3 click handler */

    } /* close the the ViewAppModel class */

    /* Here's a custom Knockout binding that makes elements shown/hidden via jQuery's fadeIn()/fadeOut() methods */
    ko.bindingHandlers.fadeVisible = {
        init: function (element, valueAccessor) {
            // Initially set the element to be instantly visible/hidden depending on the value
            var value = valueAccessor();
            $(element).toggle(ko.utils.unwrapObservable(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
        },
        update: function (element, valueAccessor) {
            // Whenever the value subsequently changes, slowly fade the element in or out
            var value = valueAccessor();
            ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
        }
    };

    var viewModel = new AppViewModel();
    ko.applyBindings(viewModel);

    viewModel.refreshClick();



    $('#uploadForm').ajaxForm({ /* prepare the ajax upload */
        beforeSend: function () {
            viewModel.loading(true);
            viewModel.uploadStatus('');
            viewModel.uploadPercent('0%');
            viewModel.uploadPercent(viewModel.uploadPercent());

        },
        uploadProgress: function (event, position, total, percentComplete) {
            viewModel.uploadPercent(percentComplete + '%');
            viewModel.uploadPercent(viewModel.uploadPercent());
        },
        complete: function (xhr) {
            viewModel.uploadStatus(xhr.responseText);
            viewModel.refreshClick();
            viewModel.uploadPage(false);
        }
    });


    /******************* jPLAYER ********************/

    function buildJplayer() {
        $("#music-player").jPlayer({
            swfPath: "Scripts/",
            supplied: "mp3",
            solution: "html, flash",
            wmode: "window"
        });
    }

    // Create click handlers for the different tracks
    $(".song-link").live("click", function (e) {
        viewModel.songListPage(false);
        viewModel.songPage(true);
        buildJplayer();
        var test = $(this).live().filter("td:parent").next(".song-artist").text();
        console.log("test: " + test);
        //viewModel.guitarArtistSearchString($(this).live().filter("td:parent").next(".song-artist").text());
        viewModel.guitarSearchString($("> span", this).live().live().text());
        viewModel.songFileName($(this).live().attr("id"));
        viewModel.searchGuitarParty();
        $("#music-player").jPlayer("setMedia", {
            mp3: "/api/song/" + $(this).live().attr("id")
        });

        $("#music-player").jPlayer("play");

        return false;
    });

});